package com.winchain.chainbill.asset.biz.credit.rx;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.base.utils.StringUtil;
import com.shell.constant.rel.AssetCode;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.governor.modules.message.keyword.CreditAssetKeyWord;
import com.winchain.chainbill.asset.biz.credit.AssetEvent;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CreditAssetMsgSubscriber extends TxSubscriber<AssetEvent<AcctTxRec>> {
	@Autowired
	private CusRecService cusRecService;

	public void onApplicationEvent(AssetEvent<AcctTxRec> t) {
		try {
			List<AcctTxRec> records = t.getRecords();
			String cusId = "";
			String currCode = "";
			BigDecimal amt = t.getTotalAmt();
			if ((records != null) && (records.size() > 0)) {
				AcctTxRec acctTxRec = (AcctTxRec) records.get(0);
				cusId = acctTxRec.getBizId();
				currCode = acctTxRec.getCurrCode();
			}
			String finId = t.getStringValue("finId");
			if ((StringUtil.emptyAndNull(cusId)) || (finId.equals(cusId))) {
				return;
			}
			String senderId;
			CreditAssetKeyWord assetKeyWord;
			String template;
			CusRec cusRec;
			senderId = CommonDataUtil.getUserId();
			assetKeyWord = new CreditAssetKeyWord();
			assetKeyWord.setCreditAmt(amt.toString());

			template = "MT02622";
			List<String> entIds = new ArrayList();
			if (AssetCode.XTB.name().equals(currCode)) {
				cusRec = (CusRec) this.cusRecService.selectByKey(cusId);
				assetKeyWord.setMemberName(cusRec.getCusName());
				template = "MT02623";
				List<CusRec> list = this.cusRecService.selectFisrSupplierByInviterId(cusId, t.getStringValue("grpId"));
				for (CusRec rec : list) {
					entIds.add(rec.getCusId());
				}
			} else {
				entIds.add(cusId);
			}
			for (String entId : entIds) {
				MessageSender.sendMessageByTmpl(senderId, template, assetKeyWord, entId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
